package ch.ams.fhnw.sudoku;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

public class SudokuTableModel extends DefaultTableModel implements TableModelListener {

	private static final long serialVersionUID = 1L;
	
	public SudokuTableModel() {
		setColumnCount(9);
		setRowCount(9);
		addTableModelListener(this);
	}
	
	public SudokuTableModel(int[][] data) {
		this();
		setSudokuData(data);
	}
	
	public void setSudokuData(int[][] data) {
		if(data == null || data.length != 9 || data[0].length != 9) {
			throw new IllegalStateException("incorrect sudoku data format");
		}
		
		int columnCount = getColumnCount();
		int rowCount = getRowCount();
		
		for (int j = 0; j < rowCount; j++) {
			for (int i = 0; i < columnCount; i++) {
				int num = data[j][i];
				if(num > 0 && num < 10) {
					setValueAt(data[j][i], j, i);
				}
			}
		}
	}

	public int[][] getSudokuData() {
		int[][] data = new int[9][9];
		
		int columnCount = getColumnCount();
		int rowCount = getRowCount();
		
		for (int j = 0; j < rowCount; j++) {
			for (int i = 0; i < columnCount; i++) {
				
				Object value = getValueAt(j, i);
				
				if(value == null) {
					data[j][i] = 0;
				} else {
					try {
						int num = Integer.parseInt(value.toString());
						data[j][i] = num;
					} catch (NumberFormatException e) {
						data[j][i] = 0;
					}
				}
			}
		}
		return data;
	}
	
	@Override
	public void setValueAt(Object value, int row, int column) {
			if(value == null) {
				return;
			}
			
			String str = value.toString();
			if(str.isEmpty()) {
				super.setValueAt(value, row, column);
				return;
			}
			
			int num;
			try {
				num = Integer.parseInt(str);
			} catch (NumberFormatException e) {
				return;
			}
			
			if(num > 0 && num < 10) {
				super.setValueAt(value, row, column);
			}
	}
	
	@Override
	public String toString() {
		StringBuffer buf = new StringBuffer();
		
		int[][] data = getSudokuData();
		
		for (int j = 0; j < data.length; j++) {
			for (int i = 0; i < data[j].length; i++) {
				int num = data[j][i];
				if(num == 0) {
					buf.append("- ");
				} else {
					buf.append(num + " ");
				}
			}
			buf.append("\n");
		}
		
		return buf.toString();
	}

	@Override
	public void tableChanged(TableModelEvent e) {
		e.getType();
	}
}


